#!/bin/bash

# MongoDB 索引优化脚本
# 用途: 创建必要的数据库索引以提升性能

echo "🗄️  DevOps SmartBot - MongoDB Index Optimization"
echo "================================================"

# MongoDB 连接信息
MONGO_HOST="localhost"
MONGO_PORT="27017"
MONGO_USER="admin"
MONGO_PASS="admin123"
MONGO_DB="devops-smart-bot"

# 连接MongoDB并执行索引创建
echo "📝 创建数据库索引..."

docker exec -i devops-mongodb mongosh \
  --username "$MONGO_USER" \
  --password "$MONGO_PASS" \
  --authenticationDatabase admin \
  <<EOF

// 切换到目标数据库
use $MONGO_DB

print("=== 开始创建索引 ===\n");

// ========== Users Collection ==========
print("📊 Users Collection:");
db.users.createIndex({ "email": 1 }, { unique: true });
print("  ✓ email (unique)");

db.users.createIndex({ "role": 1 });
print("  ✓ role");

db.users.createIndex({ "createdAt": -1 });
print("  ✓ createdAt (descending)");

// ========== Alerts Collection ==========
print("\n📊 Alerts Collection:");
db.alerts.createIndex({ "createdAt": -1 });
print("  ✓ createdAt (descending)");

db.alerts.createIndex({ "severity": 1, "status": 1 });
print("  ✓ severity + status (compound)");

db.alerts.createIndex({ "fingerprint": 1 }, { unique: true, sparse: true });
print("  ✓ fingerprint (unique, sparse)");

db.alerts.createIndex({ "labels.alertname": 1 });
print("  ✓ labels.alertname");

db.alerts.createIndex({ "labels.instance": 1 });
print("  ✓ labels.instance");

db.alerts.createIndex({ "status": 1, "startsAt": -1 });
print("  ✓ status + startsAt (compound)");

// ========== Tickets Collection ==========
print("\n📊 Tickets Collection:");
db.tickets.createIndex({ "status": 1, "priority": 1 });
print("  ✓ status + priority (compound)");

db.tickets.createIndex({ "assigneeId": 1 });
print("  ✓ assigneeId");

db.tickets.createIndex({ "createdAt": -1 });
print("  ✓ createdAt (descending)");

db.tickets.createIndex({ "relatedAlertId": 1 });
print("  ✓ relatedAlertId");

db.tickets.createIndex({ "status": 1, "createdAt": -1 });
print("  ✓ status + createdAt (compound)");

// ========== DataSources Collection ==========
print("\n📊 DataSources Collection:");
db.datasources.createIndex({ "name": 1 }, { unique: true });
print("  ✓ name (unique)");

db.datasources.createIndex({ "type": 1, "isActive": 1 });
print("  ✓ type + isActive (compound)");

// ========== Knowledge Base Collection ==========
print("\n📊 Knowledge Base Collection:");
db.knowledge.createIndex({ "title": "text", "content": "text" });
print("  ✓ title + content (text search)");

db.knowledge.createIndex({ "category": 1 });
print("  ✓ category");

db.knowledge.createIndex({ "tags": 1 });
print("  ✓ tags");

db.knowledge.createIndex({ "createdAt": -1 });
print("  ✓ createdAt (descending)");

// ========== Audit Logs Collection ==========
print("\n📊 Audit Logs Collection:");
db.auditlogs.createIndex({ "userId": 1, "createdAt": -1 });
print("  ✓ userId + createdAt (compound)");

db.auditlogs.createIndex({ "action": 1 });
print("  ✓ action");

db.auditlogs.createIndex({ "createdAt": -1 }, { expireAfterSeconds: 7776000 }); // 90天TTL
print("  ✓ createdAt (TTL: 90 days)");

// ========== 查看所有索引 ==========
print("\n📋 索引创建完成! 当前所有索引:\n");

var collections = ['users', 'alerts', 'tickets', 'datasources', 'knowledge', 'auditlogs'];
collections.forEach(function(coll) {
    var indexes = db.getCollection(coll).getIndexes();
    print("--- " + coll + " (" + indexes.length + " indexes) ---");
    indexes.forEach(function(idx) {
        print("  • " + idx.name);
    });
    print("");
});

print("=== ✅ 索引优化完成 ===");

EOF

echo -e "\n✅ 数据库索引优化完成！"
